package com.atguigu.srb.core.service.impl;

import com.alibaba.excel.EasyExcel;
import com.atguigu.srb.core.listener.ExcelDictDtoListener;
import com.atguigu.srb.core.mapper.DictMapper;
import com.atguigu.srb.core.pojo.dto.ExcelDictDto;
import com.atguigu.srb.core.pojo.entity.Dict;
import com.atguigu.srb.core.service.DictService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 数据字典 服务实现类
 * </p>
 *
 * @author 杜佳佳
 * @since 2021-04-13
 */
@Service
@Slf4j
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Transactional(rollbackFor = {Exception.class})
    @Override
    public void importData(InputStream inputStream) {
        EasyExcel.read(inputStream, ExcelDictDto.class, new ExcelDictDtoListener(baseMapper)).sheet().doRead();
    }

    @Override
    public List<ExcelDictDto> listDict() {

        List<Dict> dictList = baseMapper.selectList(null);
        List<ExcelDictDto> list = new ArrayList<>(dictList.size());

        dictList.forEach(dict -> {
            ExcelDictDto excelDictDto = new ExcelDictDto();
            BeanUtils.copyProperties(dict, excelDictDto);
            list.add(excelDictDto);
        });
        return list;
    }

    @Override
    public List<Dict> queryList(Long parentId) {

        try {
            List<Dict> dictList = (List<Dict>) redisTemplate.opsForValue().get("dictList:" + parentId);
            if(dictList != null){
                return dictList;
            }
        } catch (Exception e) {
            log.error("redis服务器异常"+ ExceptionUtils.getStackTrace(e));
        }

        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id", parentId);

        List<Dict> dictList = baseMapper.selectList(wrapper);
        dictList.forEach(dict -> {
            dict.setHasChildren(hasChildren(dict.getId()));
        });

        try {
            redisTemplate.opsForValue().set("dictList:" + parentId,dictList,1, TimeUnit.HOURS);
        } catch (Exception e) {
            log.error("redis服务器异常"+ ExceptionUtils.getStackTrace(e));
        }

        return dictList;
    }

    @Override
    public List<Dict> findByDictCode(String dictCode) {

        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("dict_code",dictCode);
        Dict dict = baseMapper.selectOne(wrapper);
        return this.queryList(dict.getId());
    }

    @Override
    public String getNameByParentCodeAndValue(String dictCode, Integer value) {

        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("dict_code",dictCode);
        Dict parentDict = baseMapper.selectOne(wrapper);
        if(parentDict == null){
            return "";
        }
        wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id",parentDict.getId())
                .eq("value",value);

        Dict dict = baseMapper.selectOne(wrapper);
        if(dict == null){
            return "";
        }
        return dict.getName();
    }

    private boolean hasChildren(Long id) {

        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id", id);
        Integer count = baseMapper.selectCount(wrapper);
        return count > 0;

    }
}
